package cn.mall.base.utils;

import cn.mall.base.exception.UserBaseException;
import cn.mall.order.utils.Utils;
import okhttp3.*;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.net.*;
import java.net.Authenticator;
import java.util.*;

public class VideoUtils {


    public static Integer convertToWan(String s){
        int videoDatad = 0;
        if(s.contains("万")){
            String numStr = s.replace("万次播放", "");
            // 将数字部分转换为浮点数
            double num = Double.parseDouble(numStr);
            videoDatad = (int)(num*10000);
            // 将浮点数乘以10000
            return videoDatad;
        }
        if(s.contains("百万")){
            String numStr = s.replace("百万次播放", "");
            // 将数字部分转换为浮点数
            double num = Double.parseDouble(numStr);
            videoDatad = (int)(num*1000000);
            // 将浮点数乘以1000000
            return videoDatad;

        } else {
            String replace = s.replace("次播放", "");
            String trim = replace.trim();
            videoDatad = Integer.parseInt(trim);
        }

        return videoDatad;
    }

    public static String dealStrv(String str){
        String[] parts = str.split("\\?");
//        System.out.println(parts[0]);
        String part = parts[0];
        String[] split = part.split("/");
        if(split[2].contains("www.weibo.com") || split[2].contains("weibo.com")){
            split[2] = "m.weibo.cn";
        }
        String url = split[0]+"//"+split[2]+"/detail/"+split[4];
        return url;
    }
    public static  AjaxResult   ToolUtils(String url ){
        try {
            //公共工具类  判断该URL是否可以解析
            String s = dealStrv(url);
            String weiboData = getWeiboData(s);
            Map<Object, Object> objectObjectMap = parseWeiboData(weiboData);
            if(objectObjectMap.isEmpty()){
                return AjaxResult.me().setSuccess(false).setMessage("无法获取数据:"+url);
            }
            String play_count = (String)objectObjectMap.get("play_count");
            return AjaxResult.me().setResultObj(play_count);

        } catch (Exception e) {
            e.printStackTrace();
            throw new UserBaseException(AjaxResult.me().setSuccess(false).setMessage("URL处理失败:获取数据失败:"+url));
        }
    }

    public static String getWeiboData(String url) throws IOException, JSONException {
        List<JSONObject> data = userIp();
        Random random = new Random();
        int randomIndex = random.nextInt(data.size());
//        System.out.println("---------");
//        System.out.println(data.get(randomIndex).toString());
        String proxyHost = data.get(randomIndex).get("ip").toString();
        String port = data.get(randomIndex).get("port").toString();
        Integer proxyPort = Integer.parseInt(port);
        String username = data.get(randomIndex).get("username").toString();
        String password = data.get(randomIndex).get("password").toString();
        java.net.Authenticator proxyAuthenticator = new java.net.Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password.toCharArray());
            }
        };
        Authenticator.setDefault(proxyAuthenticator);
        Proxy proxy = new Proxy(Proxy.Type.SOCKS, new InetSocketAddress(proxyHost, proxyPort));
        OkHttpClient client = new OkHttpClient.Builder().proxy(proxy).build();
        Request request = new Request.Builder().url(url).build();
        Response response = client.newCall(request).execute();

        return response.body().string();
    }

    public static Map<Object, Object> parseWeiboData(String html) throws JSONException {
        Map<Object, Object> map = new HashMap<>();
        Document document = Jsoup.parse(html);
//        System.out.println(document);
        Elements scriptElements = document.select("script");
        for (Element scriptElement : scriptElements) {
            String text = scriptElement.html();
            if (text.contains("$render_data")) {
                String[] vars = scriptElement.data().split("var ");
//                System.out.println(vars);
                String var = vars[2];
                var = var.replace("$render_data = [", "").replace("][0] || {};", "");
//                System.out.println(var);
                // 将处理后的字符串转换为JSONArray
                String trim = var.trim();
                JSONObject jsonObject = new JSONObject(trim);
                // 现在你可以访问jsonObject中的属性了
                JSONObject statusObject = jsonObject.getJSONObject("status");
                JSONObject page_info = statusObject.getJSONObject("page_info");
                String play_count = page_info.getString("play_count");

                map.put("play_count",play_count);

            }
        }
        return map;
    }

    public static List<JSONObject> userIp(){
        List<JSONObject> dataList = new ArrayList<>();
        String filePath = "proxy.txt"; //D:\weibo_mall\src\main\resources\proxy.txt
        try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = reader.readLine()) != null) {
                // 假设每行数据都符合 "IP----端口----username----password----时间" 的格式 ----
                // \\|
                //---
                String[] parts = line.split("----");
                if (parts.length >= 4) {
                    String ip = parts[0].trim();
                    String port = parts[1].trim();
                    String username = parts[2].trim();
                    String password = parts[3].trim();
                    // 忽略时间部分
                    // 创建JSONObject并添加到列表中
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("ip", ip);
                    jsonObject.put("port", port);
                    jsonObject.put("username", username);
                    jsonObject.put("password", password); // 注意：在实际应用中，避免存储或传输明文密码
                    dataList.add(jsonObject);
                }
            }
        } catch (IOException | JSONException e) {
            e.printStackTrace();
        }
        return dataList;
    }

}
